﻿Imports Microsoft.VisualBasic
Imports System.Diagnostics
Imports System.Data.SqlClient
Imports System.Text.RegularExpressions

Public Class FunctionClass
    Inherits System.Web.UI.Page

    Dim objConfig As New Configs
    Public objAlert As New AlertClass

    'Kiểm tra chuỗi mỗi khi cập nhật dữ liệu
    Public Function FieldCheck(ByVal sData)
        If IsDBNull(sData) Then FieldCheck = "Null" Else If Trim(sData) = "" Then FieldCheck = "Null" Else FieldCheck = "'" & Replace(Trim(sData), "'", "''") & "'"
    End Function

    'Kiểm tra chuỗi có tiếng Việt
    Public Function FieldUniCk(ByVal sData)
        If IsDBNull(sData) Then FieldUniCk = "N''" Else If Trim(sData) = "" Then FieldUniCk = "N''" Else FieldUniCk = "N'" & Replace(Trim(sData), "'", "''") & "'"
    End Function

    'Kiểm tra chuỗi có tiếng Việt
    Public Function FieldUniCkTable(ByVal sData)
        If IsDBNull(sData) Then FieldUniCkTable = "Null" Else If Trim(sData) = "" Then FieldUniCkTable = "Null" Else FieldUniCkTable = "N''" & Replace(Trim(sData), "'", "''") & "'"
    End Function

    'Kiểm tra trường Number mỗi khi cập nhật dữ liệu
    Public Function ValueCheck(ByVal sData)
        If IsDBNull(sData) Then ValueCheck = "Null" Else If IsNumeric(sData) Then ValueCheck = Replace(Trim(sData), ",", "") Else ValueCheck = "Null"
    End Function

    Public Function FieldSearchCheck(ByVal strIn As String) As String
        On Error GoTo ErrorHandler
        'Trường hợp dùng FieldCheck hoặc FieldUnicodeCheck bên trong FiledSearchCheck
        strIn = Trim(strIn)
        If UCase(Microsoft.VisualBasic.Left(strIn, 2)) = "N'" And Right(strIn, 1) = "'" Then
            strIn = Right(strIn, Len(strIn) - 2)
            strIn = Microsoft.VisualBasic.Left(strIn, Len(strIn) - 1)
            strIn = "N'" & "%" & strIn & "%" & "'"
            Return Replace(Replace(strIn, "*", "%"), "?", "_")
        End If
        If UCase(Microsoft.VisualBasic.Left(strIn, 2)) = "'" And Right(strIn, 1) = "'" Then
            strIn = Right(strIn, Len(strIn) - 1)
            strIn = Microsoft.VisualBasic.Left(strIn, Len(strIn) - 1)
            strIn = "'" & "%" & strIn & "%" & "'"
            Return Replace(Replace(strIn, "*", "%"), "?", "_")
        End If
        'Trường hợp dùng FieldCheck hoặc FieldUnicodeCheck bên ngoài FiledSearchCheck
        strIn = "%" & strIn & "%"
        FieldSearchCheck = Replace(Replace(strIn, "*", "%"), "?", "_")
        Exit Function
ErrorHandler:
    End Function

    Public Function FieldSearchTableCheck(ByVal strIn As String) As String
        On Error GoTo ErrorHandler
        'Trường hợp dùng FieldCheck hoặc FieldUnicodeCheck bên trong FiledSearchCheck
        strIn = Trim(strIn)
        If UCase(Microsoft.VisualBasic.Left(strIn, 2)) = "N'" And Right(strIn, 1) = "'" Then
            strIn = Right(strIn, Len(strIn) - 2)
            strIn = Microsoft.VisualBasic.Left(strIn, Len(strIn) - 1)
            strIn = "N'" & "%" & strIn & "%" & "'"
            Return Replace(Replace(strIn, "*", "%"), "?", "_")
        End If
        If UCase(Microsoft.VisualBasic.Left(strIn, 2)) = "'" And Right(strIn, 1) = "'" Then
            strIn = Right(strIn, Len(strIn) - 1)
            strIn = Microsoft.VisualBasic.Left(strIn, Len(strIn) - 1)
            strIn = "'" & "%" & strIn & "%" & "'"
            Return Replace(Replace(strIn, "*", "%"), "?", "_")
        End If
        'Trường hợp dùng FieldCheck hoặc FieldUnicodeCheck bên ngoài FiledSearchCheck
        strIn = "%" & strIn & "%"
        FieldSearchTableCheck = Replace(Replace(strIn, "*", "%"), "?", "_")
        Exit Function
ErrorHandler:
    End Function

    'Kiểm tra địa chỉ Email
    Public Function CheckEmailAddress(ByVal strEmailAddress As String) As Boolean
        On Error GoTo ErrorHandler
        CheckEmailAddress = False
        Dim ExceptionEmail As New System.Text.RegularExpressions.Regex("^[A-Za-z0-9](([_\.\-]?[a-zA-Z0-9]+)*)@([A-Za-z0-9]+)(([\.\-]?[a-zA-Z0-9]+)*)\.([A-Za-z]{2,})$")
        If ExceptionEmail.IsMatch(strEmailAddress) Then
            CheckEmailAddress = True
        Else
            CheckEmailAddress = False
        End If
        Exit Function
ErrorHandler:
        CheckEmailAddress = False
    End Function

    Public Function formatDateVNtoGlobal(ByVal strDate As String) As Date
        Dim objFormat As New Globalization.DateTimeFormatInfo
        'objFormat.ShortDatePattern = "yyyy-MM-dd"
        objFormat.ShortDatePattern = "dd-MM-yyyy"
        Return Date.Parse(strDate, objFormat, Globalization.DateTimeStyles.None)
    End Function

    Public Function CheckVnDate(ByVal strDate As String, Optional ByRef dtDate As Date = Nothing) As Boolean
        Dim objFormat As New Globalization.DateTimeFormatInfo
        objFormat.ShortDatePattern = "dd-MM-yyyy"
        Return Date.TryParse(strDate, objFormat, Globalization.DateTimeStyles.None, dtDate)
    End Function

    Public Function CheckTextInput(ByVal strCheck As String) As Boolean
        On Error GoTo ErrorHandler
        CheckTextInput = False
        Dim ExceptionCheck As New System.Text.RegularExpressions.Regex("[][!""#$%&'()*+,./:;<=>?@\^_`{|}~-]")
        If ExceptionCheck.IsMatch(strCheck) Then
            CheckTextInput = True
        Else
            CheckTextInput = False
        End If
        Exit Function
ErrorHandler:
        CheckTextInput = False
    End Function

    'Chuyển từ font Unicode Entity sang Unicode UTF-8
    Public Function QuoteToUnicode(ByVal iStr As String, Optional ByVal MaxLen As Long = 100000) As String
        Dim p0 As Long, p1 As Long, p2 As Long
        Dim Stt As String

        p0 = 1
        Do While p0 < MaxLen
            p1 = Microsoft.VisualBasic.InStr(p0, iStr.ToString, "&", CompareMethod.Text)
            If p1 = 0 Then Exit Do
            p2 = InStr(p1, iStr, ";", CompareMethod.Text)
            If p2 = 0 Then GoTo SkipNext

            If Mid$(iStr, p1 + 1, 1) = "#" Then
                Stt = Mid$(iStr, p1 + 2, p2 - p1 - 2)
                If Not IsNumeric(Stt) Then GoTo SkipNext

                Select Case Stt
                    Case "208"
                        iStr = Left$(iStr, p1 - 1) & ChrW(272) & Mid$(iStr, p2 + 1)
                    Case "462"
                        iStr = Left$(iStr, p1 - 1) & ChrW(259) & Mid$(iStr, p2 + 1)
                    Case Else
                        iStr = Left$(iStr, p1 - 1) & ChrW(CLng(Stt)) & Mid$(iStr, p2 + 1)
                End Select
            Else
                Stt = Mid$(iStr, p1 + 1, p2 - p1 - 1)
                Select Case Stt
                    Case "quot"
                        iStr = Left$(iStr, p1 - 1) & """" & Mid$(iStr, p2 + 1)
                    Case "amp"
                        iStr = Left$(iStr, p1 - 1) & "&" & Mid$(iStr, p2 + 1)
                    Case "lt"
                        iStr = Left$(iStr, p1 - 1) & "<" & Mid$(iStr, p2 + 1)
                    Case "gt"
                        iStr = Left$(iStr, p1 - 1) & ">" & Mid$(iStr, p2 + 1)
                End Select
            End If

SkipNext:
            p0 = p1 + 1
        Loop

        If Len(iStr) > MaxLen Then
            p1 = InStrRev(iStr, " ", MaxLen)
            p2 = InStrRev(iStr, vbCr, MaxLen)
            If p1 = 0 And p2 = 0 Then
                p1 = MaxLen
            ElseIf p1 > 0 And p2 > 0 Then
                If p1 > p2 Then p1 = p2
            ElseIf p1 = 0 And p2 > 0 Then
                p1 = p2
            End If
            QuoteToUnicode = Left(iStr, p1)
        Else
            QuoteToUnicode = iStr
        End If
    End Function

    'Chuyển từ font Unicode UTF-8 sang Unicode Entity
    Public Function UnicodeToQuote(ByVal strEncode As String) As String
        Dim oStr As String, p1 As Long, p2 As Long, CharCode As Integer
        p2 = Len(strEncode)
        p1 = 0
        oStr = ""
        Do While p1 < p2
            CharCode = Microsoft.VisualBasic.AscW(strEncode.Substring(p1, 1))
            If CharCode = 34 Then oStr += "&quot;"
            If CharCode = 38 Then oStr += "&amp;"
            If CharCode = 60 Then oStr += "&lt;"
            If CharCode = 62 Then oStr += "&gt;"
            If CharCode >= 32 And CharCode < 128 Then oStr += strEncode.Substring(p1, 1) Else oStr += "&#" & CharCode & ";"
            p1 = p1 + 1
        Loop
        UnicodeToQuote = oStr
    End Function

    'Chuyển từ font Unicode UTF-8 sang Unicode không dấu
    Public Function UnicodeToPlain(ByVal strEncode As String) As String
        Dim oStr As String, p1 As Integer, p2 As Integer
        p2 = Len(strEncode)
        p1 = 0
        oStr = ""
        Do While p1 < p2
            Select Case strEncode.Substring(p1, 1)
                Case "à", "á", "ạ", "ả", "ã", "ă", "ằ", "ắ", "ẳ", "ặ", "ẵ", "â", "ầ", "ấ", "ẩ", "ẫ", "ậ"
                    oStr += "a"
                Case "À", "Á", "Ạ", "Ả", "Ã", "Ă", "Ằ", "Ắ", "Ẳ", "Ặ", "Ẵ", "Â", "Ầ", "Ấ", "Ẩ", "Ẫ", "Ậ"
                    oStr += "A"
                Case "è", "é", "ẹ", "ẻ", "ẽ", "ê", "ề", "ế", "ể", "ệ", "ễ"
                    oStr += "e"
                Case "È", "É", "Ẹ", "Ẻ", "Ẽ", "Ê", "Ề", "Ế", "Ể", "Ệ", "Ễ"
                    oStr += "E"
                Case "ò", "ó", "ọ", "ỏ", "õ", "ơ", "ờ", "ớ", "ở", "ợ", "ỡ", "ô", "ồ", "ố", "ổ", "ộ", "ỗ"
                    oStr += "o"
                Case "Ò", "Ó", "Ọ", "Ỏ", "Õ", "Ơ", "Ờ", "Ớ", "Ở", "Ợ", "Ỡ", "Ô", "Ồ", "Ố", "Ổ", "Ộ", "Ỗ"
                    oStr += "O"
                Case "ù", "ú", "ụ", "ủ", "ũ", "ư", "ừ", "ứ", "ử", "ự", "ữ"
                    oStr += "u"
                Case "Ù", "Ú", "Ụ", "Ủ", "Ũ", "Ư", "Ừ", "Ứ", "Ử", "Ự", "Ữ"
                    oStr += "U"
                Case "ỳ", "ý", "ỵ", "ỷ", "ỹ"
                    oStr += "y"
                Case "Ỳ", "Ý", "Ỵ", "Ỷ", "Ỹ"
                    oStr += "Y"
                Case "ì", "í", "ị", "ỉ", "ĩ"
                    oStr += "i"
                Case "Ì", "Í", "Ị", "Ỉ", "Ĩ"
                    oStr += "I"
                Case "đ" : oStr += "d"
                Case "Đ" : oStr += "D"
                Case Else
                    oStr += strEncode.Substring(p1, 1)
            End Select
            p1 = p1 + 1
        Loop
        UnicodeToPlain = oStr
    End Function

    ' Xóa các ký tự đặc biệt
    Public Function ClearSpecialSymbol(ByVal strInput As String) As String
        Return strInput.Replace("!", "").Replace("@", "").Replace("#", "").Replace("$", "").Replace("%", "").Replace("^", "").Replace("&", "").Replace("*", "").Replace("(", "").Replace(")", "").Replace("|", "").Replace("?", "")
    End Function

    'Hàm check và sử dụng Microsoft Search trong SQL Server
    Public Function GetSearchStr(Optional ByVal iStr As String = "") As String
        Dim p0, p1, p2, Stt As Long
        p0 = 1
        Do
            p1 = InStr(p0, iStr, "&#", CompareMethod.Text)
            If p1 = 0 Then Exit Do
            p2 = InStr(p1, iStr, ";", CompareMethod.Text)
            If p2 = 0 Then
                p0 = p1 + 2
            Else
                Stt = Mid(iStr, p1 + 2, p2 - p1 - 2)
                If IsNumeric(Stt) Then
                    iStr = Left(iStr, p1 - 1) & ChrW(CLng(Stt)) & Mid(iStr, p2 + 1)
                    p0 = p1 + 1
                Else
                    p0 = p2 + 1
                End If
            End If
        Loop
        Do While InStr(iStr, "  ")
            iStr = Replace(iStr, "  ", " ")
        Loop

        iStr = Replace(iStr, """ """, """ and """)
        If InStr(iStr, ",") > 0 Then
            iStr = """" & Replace(iStr, ",", """ or """) & """"
        End If

        Return iStr
    End Function

    'Đọc chuỗi từ file
    Public Function ReadFile(ByVal strFilename As String) As String
        On Error GoTo ErrorHandle

        If Not System.IO.File.Exists(strFilename) Then Return ""
        Dim sr As System.IO.StreamReader = New System.IO.StreamReader(strFilename)
        Dim TextLine As String, oString As String = ""
        Do
            TextLine = sr.ReadLine()
            If Not TextLine Is Nothing Then oString += vbCrLf & TextLine
        Loop Until TextLine Is Nothing
        sr.Close()
        sr = Nothing
        ReadFile = oString
        Exit Function

ErrorHandle:
        sr.Close()
    End Function

    'Đọc file
    Public Function ReadEndFile(ByVal strFilename As String) As String
        If Not System.IO.File.Exists(strFilename) Then Return "File not found 123: " & strFilename
        Dim sr As System.IO.StreamReader = New System.IO.StreamReader(strFilename)
        Try
            Dim strContent As String = ""
            strContent = sr.ReadToEnd()
            sr.Close()
            sr = Nothing
            ReadEndFile = strContent
            Exit Function
        Catch ex As Exception
            sr.Close()
            Return "Error when read file: " & ex.Message
        End Try
    End Function

    'Tạo file trong chương trình
    Public Function CreateFile(ByVal strFilename As String, ByVal strContent As String) As Boolean
        Try
            CreateFile = False
            'Kiểm tra sự tồn tại của thư mục
            If Not System.IO.Directory.Exists(Left(strFilename, InStrRev(strFilename, "\", Len(strFilename)))) Then
                'Tạo thư mục
                Call System.IO.Directory.CreateDirectory(Left(strFilename, InStrRev(strFilename, "\", Len(strFilename))))
            End If

            Dim sFileCreate As System.IO.StreamWriter = New System.IO.StreamWriter(strFilename)
            sFileCreate.WriteLine(strContent)
            sFileCreate.Close()
            CreateFile = True
            Exit Function
        Catch ex As Exception
            If objConfig.Developer.Equals("1") Then
                objAlert.ErrorBox(Page, "File: " & (New System.Diagnostics.StackTrace).GetFrame(0).GetMethod.DeclaringType.Name & _
                                  " --- Function: " & (New System.Diagnostics.StackTrace).GetFrame(0).GetMethod.Name & _
                                  " --- Mess: " & ex.Message.Replace("'", """"))
            Else
                objAlert.ErrorBox(Page, "Lỗi kỹ thuật, hãy thông báo lại với Admin, xin cảm ơn.")
            End If
        End Try
    End Function

    'Hàm mã hóa MD5
    Public Function Hash(ByVal InputText As String) As String
        Dim MD5 As New System.Security.Cryptography.MD5CryptoServiceProvider
        If Trim(InputText) = "" Then Return ""
        Dim arrInput() As Byte
        arrInput = System.Text.UnicodeEncoding.UTF8.GetBytes(InputText)
        Dim arrOutput() As Byte
        arrOutput = MD5.ComputeHash(arrInput)
        Return Convert.ToBase64String(arrOutput)
    End Function

    'Ghi lại hành động của người sử dụng vào log file
    Public Shared Sub WriteLogToTxt(Optional ByVal AppPath As String = "", Optional ByVal sAction As String = "")
        On Error GoTo ErrorHandle
        Dim sLogFile As System.IO.StreamWriter

        Dim sDay As String = Format(Now(), "dd"), sMonth As String = Format(Now(), "MM")

        Dim strLogFileName As String = sDay & "-" & sMonth & "-" & Year(Now()) & ".log"
        Dim strFolderName As String = AppPath & "\Log\" & Year(Now()) & "-" & sMonth

        'Application.StartupPath
        'Tạo thư mục nếu chưa có
        If Not System.IO.Directory.Exists(strFolderName & "\") Then System.IO.Directory.CreateDirectory(strFolderName & "\")

        strLogFileName = strFolderName & "\" & strLogFileName
        If System.IO.File.Exists(strLogFileName) Then
            'Nếu đã tồn tại file thì tiếp tục ghi thêm
            sLogFile = System.IO.File.AppendText(strLogFileName)
            sLogFile.WriteLine(Format(Now(), "hh:mm:ss tt") & " : " & sAction)
            sLogFile.Flush()
        Else
            'Nếu file chưa tồn tại thì có thể tạo mới và ghi log
            sLogFile = New System.IO.StreamWriter(strLogFileName)
            sLogFile.WriteLine(Format(Now(), "hh:mm:ss tt") & " : " & sAction)
        End If

        sLogFile.Close()
        Exit Sub
ErrorHandle:
        If Not sLogFile Is Nothing Then sLogFile.Close()
    End Sub

    'Ghi lại file js
    Public Shared Sub WriteVal(Optional ByVal AppPath As String = "", Optional ByVal fileName As String = "", Optional ByVal sContent As String = "")
        On Error GoTo ErrorHandle
        Dim sLogFile As System.IO.StreamWriter

        Dim strFileName As String = fileName
        Dim strFolderName As String = AppPath

        'Tạo thư mục nếu chưa có
        If Not System.IO.Directory.Exists(AppPath & "\") Then System.IO.Directory.CreateDirectory(AppPath & "\")
        strFileName = strFolderName & "\" & strFileName
        If System.IO.File.Exists(strFileName) Then
            Dim f As New System.IO.FileInfo(strFileName)
            f.Delete()
        End If
        If sContent <> String.Empty Then
            sLogFile = New System.IO.StreamWriter(strFileName)
            sLogFile.Write(sContent)
            sLogFile.Close()
        End If
        Exit Sub
ErrorHandle:
        If Not sLogFile Is Nothing Then sLogFile.Close()
    End Sub

    Public Function getFileSize(ByVal Size As Long) As String
        Dim dblSize As Double
        Dim strUnit
        If Size * 1.0 / 1024 > 1 Then
            dblSize = Size * 1.0 / 1024
            strUnit = "KB"
            If dblSize / 1024 > 1 Then
                dblSize = dblSize * 1.0 / 1024
                strUnit = "MB"
            End If
        Else
            strUnit = "byte"
        End If
        Return Format(dblSize, "#,###,###.##") & " " & strUnit
    End Function

    Public Function UnicodeToNoneMark(ByVal iInput As String) As String
        If iInput Is Nothing Then Return vbNullString
        If iInput.Length <= 0 Then Return vbNullString
        iInput = iInput.ToLower
        Dim strOutput As New System.Text.StringBuilder
        Dim strMark As String = ""
        Dim strChar As String
        For i As Integer = 0 To iInput.Length - 1
            strChar = iInput.Substring(i, 1)
            Select Case strChar
                Case "â", "ê", "ô", "đ" : strOutput.Append(UnicodeToPlain(strChar)).Append(UnicodeToPlain(strChar))
                Case "ấ", "ế", "ố" : strOutput.Append(UnicodeToPlain(strChar)).Append(UnicodeToPlain(strChar)) : strMark = "s"
                Case "ầ", "ề", "ồ" : strOutput.Append(UnicodeToPlain(strChar)).Append(UnicodeToPlain(strChar)) : strMark = "f"
                Case "ẩ", "ể", "ổ" : strOutput.Append(UnicodeToPlain(strChar)).Append(UnicodeToPlain(strChar)) : strMark = "r"
                Case "ẫ", "ễ", "ỗ" : strOutput.Append(UnicodeToPlain(strChar)).Append(UnicodeToPlain(strChar)) : strMark = "x"
                Case "ậ", "ệ", "ộ" : strOutput.Append(UnicodeToPlain(strChar)).Append(UnicodeToPlain(strChar)) : strMark = "j"
                Case "ă", "ư", "ơ" : strOutput.Append(UnicodeToPlain(strChar)).Append("w")
                Case "ắ", "ứ", "ớ" : strOutput.Append(UnicodeToPlain(strChar)).Append("w") : strMark = "s"
                Case "ằ", "ừ", "ờ" : strOutput.Append(UnicodeToPlain(strChar)).Append("w") : strMark = "f"
                Case "ẳ", "ử", "ở" : strOutput.Append(UnicodeToPlain(strChar)).Append("w") : strMark = "r"
                Case "ẵ", "ữ", "ỡ" : strOutput.Append(UnicodeToPlain(strChar)).Append("w") : strMark = "x"
                Case "ặ", "ự", "ợ" : strOutput.Append(UnicodeToPlain(strChar)).Append("w") : strMark = "j"
                Case "á", "é", "í", "ó", "ú", "ý" : strOutput.Append(UnicodeToPlain(strChar)) : strMark = "s"
                Case "à", "è", "ì", "ò", "ù", "ỳ" : strOutput.Append(UnicodeToPlain(strChar)) : strMark = "f"
                Case "ả", "ẻ", "ỉ", "ỏ", "ủ", "ỷ" : strOutput.Append(UnicodeToPlain(strChar)) : strMark = "r"
                Case "ã", "ẽ", "ĩ", "õ", "ũ", "ỹ" : strOutput.Append(UnicodeToPlain(strChar)) : strMark = "x"
                Case "ạ", "ẹ", "ị", "ọ", "ụ", "ỵ" : strOutput.Append(UnicodeToPlain(strChar)) : strMark = "j"
                Case "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"
                    strOutput.Append(strChar)
                Case Else
                    strOutput.Append(strMark).Append(strChar) : strMark = ""
            End Select
        Next
        strOutput.Append(strMark)
        Return strOutput.ToString
    End Function

    Public Function SerializeObject(ByVal iObject As Object) As Byte()
        Dim bf As New System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
        Dim ms As New System.IO.MemoryStream
        bf.Serialize(ms, iObject)
        ms.Flush()
        ms.Position = 0
        Dim bytBuffer(ms.Length) As Byte
        ms.Read(bytBuffer, 0, ms.Length)
        ms.Close()
        ms = Nothing
        bf = Nothing
        Return bytBuffer
    End Function

    Public Function DeserializeObject(ByVal iInput As Byte()) As Object
        Dim ms As New System.IO.MemoryStream(iInput)
        Dim bf As New System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
        DeserializeObject = bf.Deserialize(ms)
        bf = Nothing
        ms.Close()
        ms = Nothing
    End Function

    Public Function convertDateVNtoOther(ByVal input As String, ByVal format As String) As String
        Dim dd, mm, yy As String
        ' Vi du String input = '29-08-1985'
        'dd = 29 (lay o giua tu vi tri thu 1 va lay 2 ky tu)
        dd = Mid(input, 1, 2)
        'mm = 08 (lay o giua tu vi tri thu 4 va lay 2 ky tu)
        mm = Mid(input, 4, 2)
        'yy = 1985 (lay o giua tu vi tri thu 7 va lay 4 ky tu)
        yy = Mid(input, 7, 4)
        If format = "mdy" Then
            ' return ve co dang '08-29-1985'
            Return mm & "-" & dd & "-" & yy
        ElseIf format = "ymd" Then
            ' return ve co dang '1985-08-29'
            Return yy & "-" & mm & "-" & dd
        Else
            ' return ve co dang '29-08-1985'
            Return dd & "-" & mm & "-" & yy
        End If
    End Function

    Public Function BoolToInt(ByVal flag As Boolean) As Integer
        If flag Then
            Return 1
        Else
            Return 0
        End If
    End Function

    'Lấy tên file + đường dẫn để save file
    Public Function GetUploadFileName(ByVal strPath As String, ByVal strFilename As String, Optional ByVal AddDatePath As Boolean = False) As String
        'Khai báo biến Regular Expression
        Dim MatchResults As System.Text.RegularExpressions.Match

        Dim strAdditionFolder As String = IIf(AddDatePath, Format(Now(), "\\yyyy\\MM\\dd\\"), "")
        Dim strSaveFile As String = strFilename
        Dim strSaveFolder As String = strPath & strAdditionFolder

        Try
            'Kiểm tra sự tồn tại của thư mục
            If Not System.IO.Directory.Exists(strSaveFolder) Then
                'Tạo thư mục
                Call System.IO.Directory.CreateDirectory(strSaveFolder)
            End If
            'Kiểm tra nếu file đã tồn tại thì tạo tên khác
            While System.IO.File.Exists(strSaveFolder & strSaveFile)
                MatchResults = System.Text.RegularExpressions.Regex.Match(strSaveFile, "(?<FileName>.*?)(?:\((?<AutoNumber>\d*?)\))?\.(?<FileType>\w*?)(?!.)")
                If MatchResults.Success Then
                    If MatchResults.Groups("AutoNumber").Value = vbNullString Then
                        strSaveFile = MatchResults.Groups("FileName").Value & "(1)." & MatchResults.Groups("FileType").Value
                    Else
                        strSaveFile = MatchResults.Groups("FileName").Value & "(" & (Integer.Parse(MatchResults.Groups("AutoNumber").Value) + 1).ToString & ")." & MatchResults.Groups("FileType").Value
                    End If
                End If
            End While
        Catch ex As Exception
            Throw ex
        End Try
        'tmpUploadFile.VirtualPath = strAdditionFolder.Replace("\", "/") & strSaveFile
        'tmpUploadFile.Filename = strSaveFile
        'tmpUploadFile.FullPath = strSaveFolder & strSaveFile
        Return strSaveFile
    End Function

    ' Format định dạng tiền VND trên Grid
    Public Function formatVNCurrency(ByVal currency As String) As String
        Dim temp As Double = Double.Parse(currency)
        Return String.Format("{0:#,##0}", temp)
    End Function

    ' Format định dạng tiền VND trên Grid
    Public Function StringToBool(ByVal input As String) As Boolean
        If input.Equals("1") Then
            Return True
        Else
            Return False
        End If
    End Function

    ' Cắt chuỗi them độ dài truyền vào, nếu dài hơn thì cắt
    Public Function CutStringByInterger(ByVal srt As String, ByVal longStr As Integer) As String
        If srt.Length > longStr Then
            srt = srt.Substring(0, longStr) & "..."
        End If
        Return srt
    End Function

    ' Hàm built link ảnh dựa trên datetime và tên ảnh
    Public Function buildImageByDate(ByVal strDate As String, ByVal strImg As String) As String
        If strImg = "" Then
            Return "/static/inSite/images/noimage.jpg"
        Else
            Dim d1 As Date = Date.Parse(strDate)
            Dim strSaveFolder As String = "/EditorData/image" & Format(d1, "/yyyy/MM/dd/")
            Return strSaveFolder & strImg
        End If
    End Function

    ' Hàm format date time theo dạng Việt Nam
    Function formatDateTimeToTemplate(ByVal inputStrDate As String, ByVal template As String) As String
        Try
            Dim inputDate As Date = Date.Parse(inputStrDate)
            Dim DoW As String = ""
            Select Case inputDate.DayOfWeek
                Case 0
                    DoW = "Chủ Nhật"
                Case 1
                    DoW = "Thứ 2"
                Case 2
                    DoW = "Thứ 3"
                Case 3
                    DoW = "Thứ 4"
                Case 4
                    DoW = "Thứ 5"
                Case 5
                    DoW = "Thứ 6"
                Case Else
                    DoW = "Thứ 7"
            End Select
            Dim YYYY As String = inputDate.Year
            Dim MM As String = ""
            If inputDate.Month < 10 Then
                MM = "0" & inputDate.Month
            Else
                MM = inputDate.Month
            End If
            Dim D As String = ""
            If inputDate.Day < 10 Then
                D = "0" & inputDate.Day
            Else
                D = inputDate.Day
            End If
            Dim HH As String = ""
            If inputDate.Hour < 10 Then
                HH = "0" & inputDate.Hour
            Else
                HH = inputDate.Hour
            End If
            Dim mi As String = ""
            If inputDate.Minute < 10 Then
                mi = "0" & inputDate.Minute
            Else
                mi = inputDate.Minute
            End If

            Dim ss As String = inputDate.Second

            template = template.Replace("YYYY", YYYY)
            template = template.Replace("MM", MM)
            template = template.Replace("DD", D)
            template = template.Replace("DoW", DoW)
            template = template.Replace("hh", HH)
            template = template.Replace("mm", mi)
            template = template.Replace("ss", ss)
            Return template
        Catch ex As Exception

        End Try
    End Function
#Region "Các hàm dành cho VALIDATE"
    ' Function to test for Positive Integers.
    Public Function IsNaturalNumber(ByVal strNumber As [String]) As Boolean
        Dim objNotNaturalPattern As New Regex("[^0-9]")
        Dim objNaturalPattern As New Regex("0*[1-9][0-9]*")
        Return Not objNotNaturalPattern.IsMatch(strNumber) AndAlso objNaturalPattern.IsMatch(strNumber)
    End Function

    ' Function to test for Positive Integers with zero inclusive
    Public Function IsWholeNumber(ByVal strNumber As [String]) As Boolean
        Dim objNotWholePattern As New Regex("[^0-9]")
        Return Not objNotWholePattern.IsMatch(strNumber)
    End Function

    ' Function to Test for Integers both Positive & Negative
    Public Function IsInteger(ByVal strNumber As [String]) As Boolean
        Dim objNotIntPattern As New Regex("[^0-9-]")
        Dim objIntPattern As New Regex("^-[0-9]+$|^[0-9]+$")
        Return Not objNotIntPattern.IsMatch(strNumber) AndAlso objIntPattern.IsMatch(strNumber)
    End Function

    ' Function to Test for Positive Number both Integer & Real
    Public Function IsPositiveNumber(ByVal strNumber As [String]) As Boolean
        Dim objNotPositivePattern As New Regex("[^0-9.]")
        Dim objPositivePattern As New Regex("^[.][0-9]+$|[0-9]*[.]*[0-9]+$")
        Dim objTwoDotPattern As New Regex("[0-9]*[.][0-9]*[.][0-9]*")
        Return Not objNotPositivePattern.IsMatch(strNumber) AndAlso objPositivePattern.IsMatch(strNumber) AndAlso Not objTwoDotPattern.IsMatch(strNumber)
    End Function

    ' Function to test whether the string is valid number or not
    Public Function IsNumber(ByVal strNumber As [String]) As Boolean
        Dim objNotNumberPattern As New Regex("[^0-9.-]")
        Dim objTwoDotPattern As New Regex("[0-9]*[.][0-9]*[.][0-9]*")
        Dim objTwoMinusPattern As New Regex("[0-9]*[-][0-9]*[-][0-9]*")
        Dim strValidRealPattern As [String] = "^([-]|[.]|[-.]|[0-9])[0-9]*[.]*[0-9]+$"
        Dim strValidIntegerPattern As [String] = "^([-]|[0-9])[0-9]*$"
        Dim objNumberPattern As New Regex("(" & strValidRealPattern & ")|(" & strValidIntegerPattern & ")")
        Return Not objNotNumberPattern.IsMatch(strNumber) AndAlso Not objTwoDotPattern.IsMatch(strNumber) AndAlso Not objTwoMinusPattern.IsMatch(strNumber) AndAlso objNumberPattern.IsMatch(strNumber)
    End Function

    ' Function To test for Alphabets.
    Public Function IsAlpha(ByVal strToCheck As [String]) As Boolean
        Dim objAlphaPattern As New Regex("[^a-zA-Z]")
        Return Not objAlphaPattern.IsMatch(strToCheck)
    End Function

    ' Function to Check for AlphaNumeric.
    Public Function IsAlphaNumeric(ByVal strToCheck As [String]) As Boolean
        Dim objAlphaNumericPattern As New Regex("[^a-zA-Z0-9]")
        Return Not objAlphaNumericPattern.IsMatch(strToCheck)
    End Function

    ' Function to Check full name.
    Public Function IsFullname(ByVal strToCheck As [String]) As Boolean
        Dim objAlphaNumericPattern As New Regex("/^[a-z][a-z\']+,\s?[a-z][a-z\'\.]+$/i")
        Return Not objAlphaNumericPattern.IsMatch(strToCheck)
    End Function
#End Region



#Region "Logging"
    ' logAction: 0 = Xóa, 1 = Thêm mới, 2 = Update, 3 = thao tác khác (login,sắp xếp, ..)
    Public Sub writeLog(ByVal userID As String, ByVal logAction As Integer, ByVal field1 As String, Optional ByVal field2 As String = "", Optional ByVal field3 As String = "")
        If objConfig.log.Equals("anhdp1985") Then
            Try
                Dim Sql As String = ""
                Dim cnn As String = objConfig.getConn
                Dim objData As New DatabaseClass(cnn)
                Sql = "spi_LogCreate "
                Sql &= ValueCheck(userID) & ", "
                Sql &= ValueCheck(logAction) & ", "
                Sql &= FieldUniCk(field1) & ", "
                Sql &= FieldUniCk(field2) & ", "
                Sql &= FieldUniCk(field3)
                objData.ExeNonQuery(Sql)
            Catch ex As Exception
            End Try
        End If
    End Sub
#End Region

#Region "FORMAT TEXT"
    ' Format Status trên Grid View
    Public Function formatStt(ByVal stt As Integer) As String
        If stt = 1 Then
            Return "<span style=""font-weight:bold;color: #00CC00""><b>Hoạt động</b></span>"
        Else
            Return "<span style=""font-weight:bold;color: #FF0000""><b>Khóa \ Tạm dừng</span>"
        End If
    End Function

#End Region

    Public Sub Set_Page_FB(ByVal page As Page, ByVal addUrl As String, ByVal addTitle As String, ByVal addImg As String, ByVal addDesc As String)
        addTitle = addTitle.Replace("'", "")
        addTitle += " - tynnyl.com"
        Dim ctlTitle As HtmlMeta = TryCast(page.Header.FindControl("idOgIitle"), HtmlMeta)
        If ctlTitle IsNot Nothing Then
            ctlTitle.Attributes("content") = If(addTitle <> "", addTitle, "")
        End If

        Dim ctlImg As HtmlMeta = TryCast(page.Header.FindControl("idOgImg"), HtmlMeta)
        If ctlImg IsNot Nothing Then
            ctlImg.Attributes("content") = If(addImg <> "", addImg, "")
        End If

        Dim ctrlDesc As HtmlMeta = TryCast(page.Header.FindControl("idOgDesc"), HtmlMeta)
        If ctrlDesc IsNot Nothing Then
            ctrlDesc.Attributes("content") = addDesc
        End If
    End Sub

End Class
